<template>
  <div class="div_home">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>用户信息</span>
        <!-- <el-button style="float: right; padding: 3px 0" type="text">操作按钮</el-button> -->
      </div>
      <div class="user_list">
        <el-avatar shape="circle" :size="200" fit="fit" :src="option.img"></el-avatar>
        <div :class="DivClass" @click.self="div_mouse('click')" @mouseout.stop="div_mouse('out')" @mouseover.self="div_mouse('over')"></div>
        <div class="user_item"> 用户名 : {{user.name}} </div>
        <div class="user_item"> 性别 : {{user.sex}} </div>
        <div class="user_item"> 年龄 : {{user.age}} </div>
        <div class="user_item"> 联系方式 : {{user.phone}} </div>
        <div class="user_item"> 电子邮箱 : {{user.address}} </div>
      </div>
    </el-card>
    <!-- teb切换 -->
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="欢迎页" name="top">
        <img :src="option.img" alt="" style="width: 600px;height: 600px;">

      </el-tab-pane>

      <el-tab-pane label="修改信息" name="first">
        <!-- 信息表单 -->
        <el-form :label-position="labelPosition" status-icon label-width="80px" :model="formLabelAlign" :rules="rules" ref="ruleForm">
          <el-form-item label="名称" prop="name">
            <el-input v-model="formLabelAlign.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-select v-model="formLabelAlign.sex" placeholder="请选择性别">
              <el-option label="男" value="男"></el-option>
              <el-option label="女" value="女"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="年龄" prop="age">
            <el-input v-model.number="formLabelAlign.age"></el-input>
          </el-form-item>
          <el-form-item prop="phone" label="联系方式">
            <el-input v-model="formLabelAlign.phone"></el-input>
          </el-form-item>
          <el-form-item prop="email" label="邮箱">
            <el-input v-model="formLabelAlign.email"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            <el-button @click="resetForm('ruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 修改密码 -->
      <el-tab-pane label="修改密码" name="second">
        <el-form :model="ruleForm" status-icon :rules="rules" ref="passwordruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="密码" prop="pass">
            <el-input type="password" v-model="ruleForm.pass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="checkPass">
            <el-input type="password" v-model="ruleForm.checkPass" autocomplete="off"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="passwordForm('passwordruleForm')">提交</el-button>
            <el-button @click="passwordresetForm('passwordruleForm')">重置</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <!-- 修改头像 -->
    <el-dialog title="修改头像" :visible.sync="editAvatarDialog" width="45%">
      <el-row type="flex" justify="center">
        <div class="cropper">
          <vueCropper ref="cropper" :img="option.img" :outputSize="option.size" :outputType="option.outputType" :info="option.info" :full="option.full" :canMove="option.canMove" :canMoveBox="option.canMoveBox" :original="option.original" :autoCrop="option.autoCrop" :autoCropWidth="option.autoCropWidth" :autoCropHeight="option.autoCropHeight" :fixedBox="option.fixedBox" @realTime="realTime"></vueCropper>
        </div>
        <div class="previewBox">
          <div :style="previews.div" class="preview">
            <img :src="previews.url" :style="previews.img">
          </div>
          <el-row type="flex" justify="center">
            <el-upload action="" :show-file-list="false" :auto-upload="false" :on-change="uploadImg">
              <el-button size="mini" type="primary"> 更换头像
              </el-button>
            </el-upload>
          </el-row>
          <br>
          <el-row>
            <el-button icon="el-icon-plus" circle size="mini" @click="changeScale(1)"></el-button>
            <el-button icon="el-icon-minus" circle size="mini" @click="changeScale(-1)"></el-button>
            <el-button icon="el-icon-download" circle size="mini" @click="down('blob')"></el-button>
            <el-button icon="el-icon-refresh-left" circle size="mini" @click="rotateLeft"></el-button>
            <el-button icon="el-icon-refresh-right" circle size="mini" @click="rotateRight"></el-button>
          </el-row>
        </div>
      </el-row>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editAvatarDialog = false">取 消</el-button>
        <el-button type="primary" @click="saveEditAvatar">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios, { Axios } from 'axios'
import { VueCropper } from 'vue-cropper'
export default {
  components: { VueCropper },
  data() {
    var password1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (this.ruleForm.pass.length < 6) {
        callback(new Error('密码不能小于6位'))
      } else {
        if (this.ruleForm.checkPass !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var password2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.ruleForm.pass) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    var validatePass = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户名'))
      } else {
        if (this.formLabelAlign.name !== '') {
          this.$refs.ruleForm.validateField('checkPass')
        }
        callback()
      }
    }
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入手机号'))
      } else if (this.formLabelAlign.phone.length < 11) {
        callback(new Error('请输入正确的手机号 太短了哎'))
      } else if (this.formLabelAlign.phone.length > 11) {
        callback(new Error('请输入正确的手机号 太长了哎'))
      } else if (!/^[0-9]*$/.test(this.formLabelAlign.phone)) {
        callback(new Error('请输入正确的手机号! 你怎么能输入字母哎'))
      } else {
        callback()
      }
    }
    return {
      user_id: '', // 当前用户的id
      image: '',
      // tabs 配置项
      activeName: 'top',

      //  修改用户信息的配置
      labelPosition: 'right',
      formLabelAlign: {
        name: '',
        sex: '男',
        age: '',
        phone: '',
        email: ''
      },
      DivClass: ['avatars'],
      rules1: {},
      //  修改密码配置项
      ruleForm: {
        pass: '',
        checkPass: ''
      },
      rules: {
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ],
        age: [
          { required: true, message: '年龄不能为空' },
          { type: 'number', message: '年龄必须为数字值' }
        ],
        pass: [{ validator: password1, trigger: 'blur' }],
        checkPass: [{ validator: password2, trigger: 'blur' }],
        name: [{ validator: validatePass, trigger: 'blur' }],
        phone: [{ validator: validatePass2, trigger: 'blur' }],
        sex: []
      },
      // 用户信息
      user: {
        name: '',
        age: 0,
        sex: '',
        address: '',
        phone: ''
      },

      avatarURL: '',
      editAvatarDialog: false,
      previews: {},
      option: {
        img: '', // 裁剪图片的地址
        info: true, // 裁剪框的大小信息
        outputSize: 1, // 剪切后的图片质量（0.1-1）
        full: true, // 输出原图比例截图 props名full
        outputType: 'png', // 裁剪生成额图片的格式
        canMove: true, // 能否拖动图片
        original: false, // 上传图片是否显示原始宽高
        canMoveBox: true, // 能否拖动截图框
        autoCrop: true, // 是否默认生成截图框
        autoCropWidth: 150,
        autoCropHeight: 150,
        fixedBox: true // 截图框固定大小
      }
    }
  },
  methods: {
    // 保存头像修改
    saveEditAvatar() {
      this.editAvatarDialog = false
      this.finish('base64')
    },
    // 放大/缩小
    changeScale(num) {
      num = num || 1
      this.$refs.cropper.changeScale(num)
    },
    // 左旋转
    rotateLeft() {
      this.$refs.cropper.rotateLeft()
    },
    // 右旋转
    rotateRight() {
      this.$refs.cropper.rotateRight()
    },
    // 保存上传图片
    finish(type) {
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob(data => {
          this.avatarURL = window.URL.createObjectURL(data)
          //访问接口保存到数据库写这儿!
        })
      } else {
        this.$refs.cropper.getCropData(data => {
          // 头像保存到后台
          axios({
            url: 'http://localhost:3000/user/' + this.user_id,
            method: 'PATCH',
            data: {
              image: data
            }
          })
            .then(result => {
              this.upImage()
              console.log(result)
            })
            .catch(err => {
              console.log(err)
            })
        })
      }
    },
    // 实时预览函数
    realTime(data) {
      this.previews = data
    },
    // 下载图片
    down(type) {
      var aLink = document.createElement('a')
      aLink.download = 'author-img'
      if (type === 'blob') {
        this.$refs.cropper.getCropBlob(data => {
          aLink.href = window.URL.createObjectURL(data)
          aLink.click()
        })
      } else {
        this.$refs.cropper.getCropData(data => {
          aLink.href = data
          aLink.click()
        })
      }
    },
    // 更换头像--上传本地图片
    uploadImg(file) {
      var _this = this
      var reader = new FileReader()
      reader.onload = e => {
        let data
        if (typeof e.target.result === 'object') {
          // 把Array Buffer转化为blob 如果是base64不需要
          data = window.URL.createObjectURL(new Blob([e.target.result]))
        } else {
          data = e.target.result
        }
        _this.option.img = data
      }
      // 转化为base64
      console.log(reader.readAsDataURL(file.raw))
      // 转化为blob
      // reader.readAsArrayBuffer(file.raw)
    },
    // 鼠标移入和移出头像事件
    div_mouse(v) {
      if (v == 'over') {
        this.DivClass = ['avatar']
      }
      if (v == 'out') {
        this.DivClass = ['avatars']
      }
      if (v == 'click') {
        this.editAvatarDialog = true
      }
    },
    // 加载用户页头像
    upImage() {
      this.user_id = window.localStorage.getItem('user_id')
      axios({
        url: 'http://localhost:3000/user/' + this.user_id,
        method: 'GET'
      }).then(result => {
        this.option.img = result.data.image
        this.user.name = result.data.name
        this.user.age = result.data.age
        this.user.sex = result.data.sex
        this.user.phone = result.data.phone
        this.user.address = result.data.address

        //  懒得简写了
        this.formLabelAlign.name = result.data.name
        this.formLabelAlign.age = result.data.age
        this.formLabelAlign.sex = result.data.sex
        this.formLabelAlign.phone = result.data.phone
        this.formLabelAlign.email = result.data.address
      })
    },
    // tabs 点击
    handleClick(tab, event) {
      // console.log(tab, event)
    },
    // 个人信息表单提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          axios({
            url: 'http://localhost:3000/user/' + this.user_id,
            method: 'PATCH',
            data: {
              name: this.formLabelAlign.name,
              age: this.formLabelAlign.age,
              sex: this.formLabelAlign.sex,
              phone: this.formLabelAlign.phone,
              address: this.formLabelAlign.email
            }
          })
            .then(result => {
              this.upImage()
              // console.log(result)
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },

    //  修改密码表单提交
    passwordForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          axios({
            url: 'http://localhost:3000/user/' + this.user_id,
            method: 'PATCH',
            data: {
              password: this.ruleForm.checkPass
            }
          })
            .then(result => {
              console.log(result)
            })
            .catch(err => {
              console.log(err)
            })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    passwordresetForm(formName) {
      this.$refs[formName].resetFields()
    }
  },
  mounted() {
    // 读取用户的信息
    this.upImage()
  }
}
</script>

<style lang="less" scoped>
.div_home {
  display: flex;
}
.box-card {
  width: 460px;
  background-image: linear-gradient(120deg, #fdfbfb 0%, #ebedee 100%);
}
// 用户信息
.user_list {
  width: 400px;
  height: auto;
  margin: 0 auto;
  text-align: center;
  position: relative;
  .avatar {
    width: 200px;
    height: 200px;
    position: absolute;
    left: 100px;
    z-index: 1;
    display: inline-block;
    background-image: url('../../assets/上传头像.png');
    background-size: 50%;
    background-repeat: no-repeat;
    background-position: center;
    background-color: #72727378;
    border-radius: 50%;
  }
  .avatars {
    width: 200px;
    height: 200px;
    position: absolute;
    left: 100px;
    z-index: 1;
    display: inline-block;
    border-radius: 50%;
  }
}
.user_item {
  padding: 10px;
  font-size: 16px;
  margin-top: 8px;
}
.previewBox {
  text-align: center;
  margin-left: 80px;
}

.preview {
  width: 150px;
  height: 150px;
  margin: 0px auto 20px auto;
  border-radius: 50%;
  border: 1px solid #ccc;
  background-color: #ccc;
  overflow: hidden;
}

.cropper {
  width: 280px;
  height: 280px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
// tabs 的css
.el-tabs {
  flex: 1;
  margin-right: 100px;
  margin-left: 50px;
  .el-tabs__content {
    width: 420px;
  }
}
</style>